﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using WebHoiChoMuaBan.Models;
using System.Web.Mvc;
using System.Drawing;

namespace WebHoiChoMuaBan.Controllers.Utility
{
    public partial class ImageHelper
    {
        public bool CheckInfoIcon(HttpPostedFileBase newsImg)
        {
            // size of uploaded file must less than 1MB and larger than 0
            if (newsImg.ContentLength > 0 && newsImg.ContentLength < 1048576)
            {
                var fileName = Path.GetFileName(newsImg.FileName);
                var tailIcon = Path.GetExtension(fileName);
                if (tailIcon.Equals(".png") || tailIcon.Equals(".jpg") || tailIcon.Equals(".gif"))
                    return true;
            }
            return false;
        }

        public void DeleteImg(string fileToDelete)
        {
            FileInfo fileInfo = new FileInfo(fileToDelete);
            fileInfo.Delete();
        }

        public Bitmap ResizeImage(Stream streamImage, int maxWidth, int maxHeight)
        {
            Bitmap originalImage = new Bitmap(streamImage);
            int newWidth = originalImage.Width;
            int newHeight = originalImage.Height;
            double aspectRatio = (double)originalImage.Width / (double)originalImage.Height;

            if (aspectRatio <= 1 && originalImage.Width > maxWidth)
            {
                newWidth = maxWidth;
                newHeight = (int)Math.Round(newWidth / aspectRatio);
            }
            else if (aspectRatio > 1 && originalImage.Height > maxHeight)
            {
                newHeight = maxHeight;
                newWidth = (int)Math.Round(newHeight * aspectRatio);
            }

            Bitmap newImage = new Bitmap(originalImage, newWidth, newHeight);

            Graphics g = Graphics.FromImage(newImage);
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
            g.DrawImage(originalImage, 0, 0, newImage.Width, newImage.Height);

            originalImage.Dispose();

            return newImage;
        }

        public void uploadImage(string path, HttpPostedFileBase hpf, int width, int height)
        {
            ImageHelper imgHelper = new ImageHelper();
            if (imgHelper.CheckInfoIcon(hpf))
            {
                Bitmap image = imgHelper.ResizeImage(hpf.InputStream, width, height);
                image.Save(path);
                image.Dispose();
            }
        }
    }
}